package net.weamor.interfaces.interceptor;

import net.weamor.interfaces.global.GlobalVar;
import net.weamor.interfaces.pojo.RequestObject;
import net.weamor.interfaces.utils.Base64Kit;
import net.weamor.interfaces.utils.DataKit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Invocation;
import com.jfinal.aop.PrototypeInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.render.Render;

/** 
 * @ClassName ParamInterceptor  
 * @Description 线程安全的参数拦截器 
 *   
 */
public class ParamInterceptor extends PrototypeInterceptor {

	private Logger logger = LoggerFactory.getLogger(ParamInterceptor.class);
	public static boolean isDevMode = false;
	//是否为调试模式
	public static String devModeStr = null;
	
	
	@Override
	public void doIntercept(Invocation inv) {
		if (devModeStr == null) {
			isDevMode = Render.getDevMode();
			devModeStr =  "1";
		}
		
		//封装请求参数
		Controller controller = inv.getController();
		
		String pro = controller.getPara("pro");
		String sparam = controller.getPara("param");
		String caller = controller.getPara("caller");
		String method = controller.getPara("method");
		String head = controller.getPara("head");
		String reqEncoding = controller.getPara("reqEncoding");
		String paramstyle = controller.getPara("paramstyle");
		String reqId = controller.getPara("reqId");
		String respId = DataKit.getRandomUnique();
		String param = "";
		try {
			if (DataKit.isNotEmpty(sparam)) {
				param = Base64Kit.decodeString(sparam);
			} else if (DataKit.isNotEmpty(head)){
				head = Base64Kit.decodeString(head);
			}
		} catch (Exception e) {
			controller.renderError(GlobalVar.HTTP_500);
		}
		
		RequestObject requestParam = 
				new RequestObject(pro, param,sparam, caller, method, reqEncoding, head, paramstyle, respId, reqId);

		if (isDevMode) {
			logger.info("#I {} Receives the request requestParam:"+requestParam.toString(),reqId);
		}
		
		controller.setAttr("requestParam", requestParam);
		inv.invoke();
		if (isDevMode) {
			logger.info("#I {} Returns the request data requestParam:"+inv.getReturnValue(),reqId);
		}
	}

}
